<?php
/*
 * @分销商城
 * @功能说明：支付入口
 * @更新说明：暂无更新
 * @文件名 PayController.class.php
 * @编码 UTF-8
 * @创建时间 2016-1-22 下午6:11:17
 * @创建人 XING
 */

namespace wap\Controller;
use Think\Controller;

class PayController extends Controller {
	/*
	 * 分销商城_支付渠道设置
	 * @date: 2016-1-22 下午6:11:33
	 * @editor: XING
	 */
	public $payChannel = array(
			'alipay','alipay_wap','alipay_qr','apple_pay',
			'bfb','bfb_wap','upacp','upacp_wap','upmp','upmp_wap',
			'wx','wx_pub','wx_pub_qr','yeepay_wap','jdpay_wap','wx_new'
	);
	
	/*
	 * 分销商城_支付主体
	 * @date: 2016-1-22 下午6:12:41
	 * @editor: XING
	 */
	public function payInit(){
		!I('post.order_id') && dataFormat('',0,'订单参数缺失');
		(!I('post.money') || I('post.money') < 0) && dataFormat('',0,'订单金额有误');
		!in_array(I('post.channel'),$this->payChannel) && dataFormat('',0,'非法支付渠道');
		M('OrderEntity')->getFieldByOrderId(I('post.order_id'),'order_status') != '0' && dataFormat('',0,'非法的支付订单');
		//调用支付
		$reQuest = (new \service\ping\Ping)->payinit(I('post.order_id'),I('post.money'),I('post.channel'),session('wxopenid'.session('loginUid')));
		
		dataFormat(json_decode($reQuest,1));
    }

	/*
	 * 灯商云端_支付回调
	 * @date: 2015-11-23 下午4:02:23
	 * @editor: XING
	 */
    public function payCallback(){
    	$getParams = json_decode(file_get_contents("php://input"), true);
    	if($getParams && $getParams['type'] == 'charge.succeeded'){
    		$order_id = trim($getParams['data']['object']['metadata']['order_id']);
    		$getOrderMsg = M('OrderEntity')
    					 ->where(array('order_id'=>$order_id))->find();
    		/*在线支付金额*/
    		$cashMoney = $getParams['data']['object']['amount']/100;
    		/*支付渠道*/
    		$payChannelWay = $getParams['data']['object']['channel'];
    		/*支付凭证id*/
    		$chargeId = $getParams['data']['object']['id'];
    		//支付状态校验
    		if($getOrderMsg['order_status'] != '0'){
    			file_put_contents('log.txt', 'error status code');
    			dataFormat('',0,'非有效的支付订单');
    		}
    		if(($getOrderMsg['order_amount'] - $getOrderMsg['order_discount']) != $cashMoney){
    			file_put_contents('log.txt', $getOrderMsg['order_amount'].'-'.$getOrderMsg['order_discount'].'='.$cashMoney.' error pay money');exit;
    		}
    		$BuyerEntity = M('CustBottler');
    		$BuyerEntity->startTrans();
    		$buyerId = $BuyerEntity->lock(true)->add(array(
    				'order_id' => $order_id,
    				'finance_money' => $cashMoney,
    				'cust_id' => $getOrderMsg['cust_id'],
    				'money_remark' => '订单付款充值',
    				'is_waste' => 0,
    				'add_at' => time()
    		));
    		if($buyerId > 0){
    			$buyerBuy = $BuyerEntity->lock(true)->add(array(
    					'order_id' => $order_id,
    					'finance_money' => -($cashMoney),
    					'cust_id' => $getOrderMsg['cust_id'],
    					'money_remark' => '订单付款支出',
    					'is_waste' => 0,
    					'add_at' => time()
    			));
    			if($buyerBuy > 0){
    				$payChannel = M('PayChannel');
    				$getChannelId = $payChannel->lock(true)->add(array(
    						'order_id' => $order_id,
    						'pay_channel' => $payChannelWay,
    						'pay_money' => $cashMoney,
    						'charge_id' => $chargeId,
    						'add_at' => time()
    				));
    				if($getChannelId > 0){
    					if($getOrderMsg['order_type'] == '0'){
	    					$orderMain = M('OrderEntity');
	    					$getAffeId = $orderMain->lock(true)
	    							   ->where(array('order_id'=>$order_id))->setField(array(
			    							'order_status' => '1',
			    							'pay_at' => time(),
			    							'update_at' => time(),
			    							'pay_money' => $cashMoney
			    						));
	    					if($getAffeId){
	    						if($getOrderMsg['coupon_money'] > 0){
		    						//@todo 处理优惠信息
	    						}
	    						$goodsCollect = M('OrderCollect')
	    								      ->where(array('order_id'=>$order_id))->select();
	    						$goodsProfit = M('GoodsProfit');
	    						$goodMainEffect = M('GoodsEntity');
	    						$oemPrice = 0;$partnerId = $putProfit = 0;
								$name = '';$bizMsg = array();
	    						foreach($goodsCollect AS $key=>$vals){
	    							if($vals['type'] == '2'){
	    								$oemPrice += $vals['pay_price'] * $vals['pay_nums'];
	    							}else if($vals['type'] == '1'){
										//todo 更新支付时间
										$putProfit = $goodsProfit->lock(true)
											->where(array('goods_id'=>$vals['goods_id'],'order_id'=>$order_id))
											->setField(array('pay_at'=>time()));
										//统计所有卖家以及各店铺收益
										$bizMsg[$vals['biz_cust_id']][] = $vals['profit'] * $vals['pay_nums'];
									}
									//销量
									$goodsEffect = $goodMainEffect->lock(true)
										         ->where(array('goods_id'=>$vals['goods_id']))->setInc('sales',$vals['pay_nums']);
	    							$partnerId = $vals['biz_cust_id'];
									$name .= $vals['goods_title'].',';
	    						}
								$goods_title = (mb_substr($name,0,18,'utf-8')).'...';
	    						if(($putProfit || $oemPrice > 0) && $goodsEffect){
	    							if($oemPrice > 0){
	    								$currentUserMsg = M('CustEntity')->field('salelevel,parent_id,is_top')
	    												->where(array('cust_id'=>$getOrderMsg['cust_id']))->find();
	    								$levelMoney = 0;
	    								if($oemPrice >= 1588 && in_array($currentUserMsg['salelevel'],array('0','1'))){
	    									$paramComb = array('','2');
	    									$levelMoney = '1588';
	    									$ltype = 1;
	    								}elseif($oemPrice >= 1000 && in_array($currentUserMsg['salelevel'],array('0','1'))){
	    									if($currentUserMsg['salelevel'] == '0'){
	    										$paramComb = array('','1');
	    										$levelMoney =  '588';
	    										$ltype = 0;
	    									}else if($currentUserMsg['salelevel'] == '1'){
	    										$paramComb = array('','2');
	    										$levelMoney =  '1000';
	    										$ltype = 2;
	    									}
	    								}elseif($oemPrice >= 588 && in_array($currentUserMsg['salelevel'],array('0'))){
	    									$paramComb = array('','1');
	    									$levelMoney = '588';
	    									$ltype = 0;
	    								}else{
	    									$goodsProfit->commit();
	    									$BuyerEntity->commit();
	    									$payChannel->commit();
	    									$orderMain->commit();
	    									file_put_contents('log.txt', 'error 1011'.$order_id);
											//todo 没有升级(没有升级推送,只有商品购买推送)
											curl($_SERVER['SERVER_NAME'].'/jsssdk/buyerNew',array(
												'cust_id' => $getOrderMsg['cust_id'],
												'biz_cust_id' => $partnerId,
												'order_id' => $order_id,
												'cashMoney' => $cashMoney,
												'goods_title' => $goods_title,
												'oemPrice' => $oemPrice
											));
	    									echo '2xx';exit;
	    								}
		    							$custMains = M('CustEntity');
		    							$affectCust = $custMains->lock(true)
					    							->where(array('cust_id'=>$getOrderMsg['cust_id']))->setField(array(
					    									'salelevel' => $paramComb[1],
					    									'promit_at' => time(),
					    									'parent_id' => $currentUserMsg['is_top'] > 0 ? '0' : ($currentUserMsg['parent_id'] ?: $partnerId),
					    									'update_at' => time()
					    							));
		    							if($affectCust){
		    								if($currentUserMsg['is_top'] > 0){
		    									//顶级用户升级处理
		    									$goodsProfit->commit();
		    									$payChannel->commit();
		    									$orderMain->commit();
		    									$custMains->commit();
		    									$BuyerEntity->commit();
		    									file_put_contents('log.txt', 'error 1019'.$order_id);
		    									//@todo 顶级用户升级推送
												curl($_SERVER['SERVER_NAME'].'/jsssdk/buyerNew',array(
													'cust_id' => $getOrderMsg['cust_id'],
													'order_id' => $order_id,
													'cashMoney' => $cashMoney,
													'goods_title' => $goods_title,
													'ltype' => $ltype+1,
													'is_top' => 1
												));
		    									echo '2xx';exit;
		    								}
		    								$levelAffect = M('CustInlevel');
		    								$putProfit = 0;
		    								if($levelMoney > 0){
		    									$getBizLevel = M('CustEntity')
		    												 ->getFieldByCustId($currentUserMsg['parent_id'] ?: $partnerId,'salelevel');
		    									if($getBizLevel){
				    								$putProfit = $levelAffect->lock(true)->add(array(
				    										'money' => $levelMoney,
				    										'type' => $ltype,
				    										'cust_id' => $getOrderMsg['cust_id'],
				    										'biz_cust_id' => $currentUserMsg['parent_id'] ?: $partnerId,
				    										'biz_cust_salelevel' => $getBizLevel,
															'order_id' => $order_id,
				    										'add_at' => time()
				    								));
		    									}
		    								}
		    								if($putProfit || $levelMoney == '0'){
		    									$levelAffect->commit();
			    								$goodsProfit->commit();
			    								$payChannel->commit();
			    								$orderMain->commit();
			    								$custMains->commit();
			    								$BuyerEntity->commit();
			    								file_put_contents('log.txt', 'error 1010'.$order_id);
												//todo 升级推送
												curl($_SERVER['SERVER_NAME'].'/jsssdk/buyerNew',array(
													'cust_id' => $getOrderMsg['cust_id'],
													'biz_cust_id' => $partnerId,
													'order_id' => $order_id,
													'cashMoney' => $cashMoney,
													'goods_title' => $goods_title,
													'ltype' => $ltype+1,
													'biz_cust_salelevel' => $getBizLevel
												));
			    								echo '2xx';exit;
		    								}else{
		    									$levelAffect->rollback();
		    									$goodsProfit->rollback();
		    									$payChannel->rollback();
		    									$orderMain->rollback();
		    									$BuyerEntity->rollback();
		    									$custMains->rollback();
		    									file_put_contents('log.txt', 'error 1009'.$order_id);exit;
		    									dataFormat('',0,'流水出错');
		    								}
		    							}else{
		    								$goodsProfit->rollback();
		    								$payChannel->rollback();
		    								$orderMain->rollback();
		    								$BuyerEntity->rollback();
		    								$custMains->rollback();
		    								file_put_contents('log.txt', 'error 1008'.$order_id);exit;
		    								dataFormat('',0,'流水出错');
		    							}
	    							}else{
	    								$goodsProfit->commit();
	    								$payChannel->commit();
	    								$orderMain->commit();
	    								$BuyerEntity->commit();
	    								file_put_contents('log.txt', 'error 1007'.$order_id);
										//todo 普通商品模板推送
										curl($_SERVER['SERVER_NAME'].'/jsssdk/buyerNew',http_build_query(array(
											'cust_id' => $getOrderMsg['cust_id'],
											'biz_cust_id' => $bizMsg,
											'order_id' => $order_id,
											'cashMoney' => $cashMoney,
											'goods_title' => $goods_title,
										)));
	    								echo '2xx';exit;
	    							}
	    						}else{
	    							$goodsProfit->rollback();
	    							$payChannel->rollback();
	    							$orderMain->rollback();
	    							$BuyerEntity->rollback();
	    							file_put_contents('log.txt', 'error 1006'.$order_id);exit;
	    							dataFormat('',0,'流水出错');
	    						}
	    					}else{
	    						$payChannel->rollback();
	    						$orderMain->rollback();
	    						$BuyerEntity->rollback();
	    						file_put_contents('log.txt', 'error 1005'.$order_id);exit;
	    						dataFormat('',0,'流水出错');
	    					}
    					}elseif($getOrderMsg['order_type'] == '1' && $getOrderMsg['remark']){
    						$orderMain = M('OrderEntity');
    						$getAffeId = $orderMain->lock(true)
			    						->where(array('order_id'=>$order_id))->setField(array(
			    								'order_status' => '4',
			    								'pay_at' => time(),
			    								'update_at' => time(),
			    								'pay_money' => $cashMoney
			    						));
    						$markMsg = explode('_',$getOrderMsg['remark']);
    						if($getAffeId && $markMsg[1] == $cashMoney){
    							if($getOrderMsg['coupon_money'] > 0){
    								//@todo 处理优惠信息
    							}
    							$getBizLevel = M('CustEntity')->getFieldByCustId($markMsg[2],'salelevel');
    							$levelAffect = M('CustInlevel');
    							$putProfit = $levelAffect->lock(true)->add(array(
    										'money' => $cashMoney,
    										'type' => $markMsg[0],
    										'cust_id' => $getOrderMsg['cust_id'],
    										'biz_cust_id' => $markMsg[2],
    										'biz_cust_salelevel' => $getBizLevel,
    										'add_at' => time()
    								));
    							if($putProfit){
    								$custMains = M('CustEntity');
    								$affectCust = $custMains->lock(true)
			    								->where(array('cust_id'=>$getOrderMsg['cust_id']))->setField(array(
			    										'salelevel' => $markMsg[0] > 0 ? '2' : '1',
			    										'promit_at' => time(),
			    										'parent_id' => $markMsg[2],
			    										'update_at' => time()
			    								));
    								if($affectCust){
    									$custMains->commit();
    									$levelAffect->commit();
    									$payChannel->commit();
    									$orderMain->commit();
    									$BuyerEntity->commit();
    									file_put_contents('log.txt', 'error 1006'.$order_id);
    									echo '2xx';exit;
    								}else{
    									$custMains->rollback();
    									$levelAffect->rollback();
    									$payChannel->rollback();
    									$orderMain->rollback();
    									$BuyerEntity->rollback();
    									file_put_contents('log.txt', 'error 1010'.$order_id);exit;
    									dataFormat('',0,'流水出错');
    								}
    							}else{
    								$goodsProfit->rollback();
    								$payChannel->rollback();
    								$orderMain->rollback();
    								$BuyerEntity->rollback();
    								file_put_contents('log.txt', 'error 1008'.$order_id);exit;
    								dataFormat('',0,'流水出错');
    							}
    						}else{
    							$payChannel->rollback();
    							$orderMain->rollback();
    							$BuyerEntity->rollback();
    							file_put_contents('log.txt', 'error 1005'.$order_id);exit;
    							dataFormat('',0,'流水出错');
    						}
    					}
    				}else{
    					$payChannel->rollback();
    					$BuyerEntity->rollback();
    					file_put_contents('log.txt', 'error 1004'.$order_id);exit;
    					dataFormat('',0,'流水出错');
    				}
    			}else{
    				$BuyerEntity->rollback();
    				file_put_contents('log.txt', 'error 1003'.$order_id);exit;
    				dataFormat('',0,'流水出错');
    			}
    		}else{
    			$BuyerEntity->rollback();
    			file_put_contents('log.txt', 'error 1002'.$order_id);exit;
    			dataFormat('',0,'流水出错');
    		}
    	}else{
    		file_put_contents('log.txt', 'error 1001'.$order_id);exit;
    		dataFormat('',0,'支付失败');
    	}
    }
    
	/*
	 * 分销商城_自动确认收货
	 * @date: 2016-1-22 下午7:15:05
	 * @editor: XING
	 */
    public function putSubSave(){
    	$orderMain = M('OrderEntity');
    	$putOrder = $orderMain->field('order_id')
    			  ->where('order_status = 2 AND express_at > 0 AND express_at < '.(time()-(getSysConfig('putSavehs'))*24*3600))->select();
    	if($putOrder){
    		foreach($putOrder AS $vv){
    			$orderEffect = $orderMain->lock(true)
    						 ->where(array('order_id'=>$vv['order_id']))->setField(array(
					    		'order_status' => '4',
					    		'success_at' => time(),
					    		'update_at' => time()
				    		));
    			if($orderEffect){
    				$goodsProfit = M('GoodsProfit');
    				$putProfit = $goodsProfit->lock(true)
    						   ->where('order_id = "'.$vv['order_id'].'" AND is_profit = 0')->setField(array(
    						   			'is_profit' => '3',
    						   			'success_at' => time(),
    						   			'update_at' => time()
    						   		));
    				if($putProfit){
    					$goodsProfit->commit();
    					$orderMain->commit();
    				}else{
    					$goodsProfit->rollback();
    					$orderMain->rollback();
    				}
    			}else{
    				$orderMain->rollback();
    			}
    		}
    	}
    }
    
    /*
	 * 分销商城_自动取消订单
	 * @date: 2016-3-28 下午6:19:38
	 * @editor: XING
	 */
    public function autoCancle(){
    	$orderMain = M('OrderEntity');
    	$putOrder = $orderMain->field('order_id')
    			  ->where('order_status = 0 AND add_at > 0 AND add_at < '.(time()-(getSysConfig('orderCancle'))*60))->select();
    	if($putOrder){
    		foreach($putOrder AS $vv){
    			$orderEffect = $orderMain->lock(true)
			    			 ->where(array('order_id'=>$vv['order_id']))->setField(array(
			    					'order_status' => '-1',
			    					'update_at' => time()
			    			 ));
    			if($orderEffect){
    				$goodsCollect = M('OrderCollect')
    						      ->where(array('order_id'=>$vv['order_id']))->select();
    				if($goodsCollect){
    					$goodsMain = M('GoodsEntity');
    					foreach($goodsCollect AS $vals){
		    				$putGoods = $goodsMain->lock(true)
					    			  ->where('goods_id = "'.$vals['goods_id'].'"')->setInc('kcun',$vals['pay_nums']);
		    				if($putGoods){
		    					$goodsMain->commit();
		    					$orderMain->commit();
		    				}else{
		    					$goodsMain->rollback();
		    					$orderMain->rollback();
		    				}
    					}
    				}else{
    					$orderMain->rollback();
    				}
    			}else{
    				$orderMain->rollback();
    			}
    		}
    	}
    }
    
    /*
	 * 分销商城_支付回调
	 * @date: 2016-3-31 下午2:16:58
	 * @editor: XING
	 */
    public function refundCallBack(){
    	$getParams = json_decode(file_get_contents("php://input"), true);
    	if($getParams['type'] == 'refund.succeeded'&& $getParams['data']['object']['succeed'] == true){
    		$order_id = M('PayChannel')->getFieldByChargeId(trim($getParams['data']['object']['charge']),'order_id');
    		$getOrderMsg = M('OrderEntity')
    					 ->where(array('order_id'=>$order_id))->find();
    		if($getOrderMsg['order_status'] == '8'){
				$wecha_id =  M('CustEntity')
    					 ->where(array('cust_id'=>$getOrderMsg['cust_id']))->getField('wxsek');
				$url ='http://wap.hipaygo.cn/order/odetail/orderId/'.$order_id;
				$info=array(
					'first' =>array('value'=>'您有一笔退款','color'=>'#743A3A'),
					'reason'=>array('value'=>$getOrderMsg['refund_content'],'color'=>'#743A3A'),
					'refund'=>array('value'=>$getOrderMsg['refund_mon'],'color'=>"#743A3A"),
					'remark'=>array('value'=>'点击查看订单详情','color'=>'#743A3A')
				); 
				$msg = (new JsssdkController())->msg('-qIyus9CWYOnGmx_KkIHHELZ9heZlyT6E-fw_yRmkXQ',$info,$wecha_id,$url,'#7B68EE');
    			echo '2xx';exit;
    		}else{
    			exit('fail');
    		}
    	}else{
    		file_put_contents('refundCode.txt', ' order_id:'.$order_id.', code: 0000 ');
    		dataFormat('',0,'支付失败');
    	}
    }    
}